<template>
	<div class="login_box">
		<el-form ref="loginFormRef" label-width="80px" :model="form" :rules="rules">
		  <el-form-item label="用户名" prop="username">
		    <el-input v-model="form.username" placeholder="请输入用户名" suffix-icon="el-icon-user"></el-input>
		  </el-form-item>
		  <el-form-item label="密码" prop="password">
		    <el-input v-model="form.password" placeholder="请输入密码" suffix-icon="el-icon-lock"></el-input>
		  </el-form-item> 
		  <el-form-item>
		    <el-button type="primary" @click="handleLogin('loginFormRef')">登录</el-button>
		    <el-button @click="resetForm('loginFormRef')">重置</el-button>
		  </el-form-item>
		</el-form>
	</div>
</template>

<script>
	export default {
		name: 'Login',
		data(){
			return {
				form:{
					username: 'admin',
					password: '123456'
				},
				rules: {
					username: [
						{ required: true, message: '请输入用户名', trigger: 'blur' },
						{ min: 5, max: 11, message: '长度在 5 到 11 个字符', trigger: 'blur' }
					],
					password: [
						{ required: true, message: '请输入密码', trigger: 'blur' },
						{ min: 6, max: 11, message: '长度在 6 到 15 个字符', trigger: 'blur' }
					]
				}
			}
		},
		methods: {
			 handleLogin(formName){
				this.$refs[formName].validate()
				.then(async (result) => {
					if(result){
						//请求登录接口
						const { data: res } = await this.$axios.post('/login', this.form)
						 
						//本地缓存token
						window.sessionStorage.setItem('token', res.data.token)
						 
						//跳转到主页
						this.$router.push('/home')
					}
				})
				.catch((err) => {
					return
				})
			},
			resetForm(formName){
				this.$refs[formName].resetFields() 
			}
		}
	}
</script>

<style lang="less" scoped="scoped">
	.login_box{
		position: absolute;
		left: 50%;
		top: 50%;
		transform: translate(-50%, -50%);
		padding: 20px;
		width: 400px;
		border-radius: 6px;
		background: #fff;
	}
	
	.el-form-item:nth-last-child(1){
		margin-left: 0;
		margin-bottom: 0;
		text-align: center;
		
		.el-form-item__content{
			margin-left: 0 !important;
		}
	}
</style>
